#include "stdio.h"
#include "string.h"
#include <stdlib.h>
#include "board.h"
#include "small_modbus.h"
#include "board_virtualIO.h"
#include "u_data.h"
#include "u_rtc.h"
#include "u_params.h"
#include "u_app.h"
#include "u_alarm.h"

#define DBG_TAG "HMI"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>

uint16_t hold_regs[HOLD_REG_MAX] = {0};

int vio_read_hold_regs(uint16_t addr, uint16_t num, uint16_t* buffer)
{
    uint16_t index = 0, naddr = 0, temp = 0, base = 0;
    uint16_t io_start = 0, io_end = 0;

    // LOG_I("READ:%d %d ", addr, num);

    for (index = 0; index < HOLD_REG_MAX; index++)
    {
        // 动态更新参数
        if (index < addr)
        {
            continue;
        }
        if (index > (addr + num))
        {
            break;
        }
        if (index == 0)
        {
            hold_regs[index] = 0xFF;
        }
        else
        {
            hold_regs[index] = 0x00;
        }
    }

    index = 0;
    if ((0 <= addr) && (addr < HOLD_REG_MAX))
    {
        io_start = addr;
        if ((addr + num) > (HOLD_REG_MAX))
        {
            io_end = HOLD_REG_MAX;
        }
        else
        {
            io_end = addr + num;
        }
        while (io_start < io_end)
        {
            if (naddr > 0)
            {
                buffer[index] = hold_regs[naddr];
                naddr++;
            }
            else
            {
                buffer[index] = hold_regs[io_start];
            }
            io_start++;
            index++;
        }
    }
    return index;
}

int vio_write_hold_regs(uint16_t addr, uint16_t num, uint16_t* buffer)
{
    uint16_t value = 0, temp = 0, base = 0;

    if ((0 <= addr) && (addr < HOLD_REG_MAX))
    {
        value = aio_get_val(buffer, 0);
        LOG_I("mb -> write reg addr:%d value:%d", addr, value);
        if (addr == 0)
        {
            ;
        }
    }
    return num;
}

#if 0
#define INPUT_REG_MAX 16
uint16_t input_regs[INPUT_REG_MAX] = {0};

int vio_read_input_regs(uint16_t addr, uint16_t num, uint16_t *buffer)
{
	uint16_t index = 0;
	uint16_t io_start = 0;
	uint16_t io_end = 0;
	if ((0 <= addr) && (addr < INPUT_REG_MAX))
	{
		io_start = addr;
		if ((addr + num) > (INPUT_REG_MAX))
		{
			io_end = INPUT_REG_MAX;
		}
		else
		{
			io_end = addr + num;
		}
		while (io_start < io_end)
		{
			aio_set_val(buffer, index, aio_get_val(input_regs, io_start));
			io_start++;
			index++;
		}
	}
	return index;
}

int vio_lowlevel_update_input_regs(uint16_t addr, uint16_t num, uint16_t *buffer)
{
	uint16_t index = 0;
	uint16_t io_start = 0;
	uint16_t io_end = 0;
	if ((0 <= addr) && (addr < INPUT_REG_MAX))
	{
		io_start = addr;
		if ((addr + num) > (INPUT_REG_MAX))
		{
			io_end = INPUT_REG_MAX;
		}
		else
		{
			io_end = addr + num;
		}
		while (io_start < io_end)
		{
			aio_set_val(input_regs, io_start, aio_get_val(buffer, index));
			io_start++;
			index++;
		}
	}
	return index;
}
#endif
